( function ( D )
{
    var items = [ ],
        properties = [ ];

    var findPredicates = function( )
	{
		D.request( "pages.txt", { "collection": D.collectionId },
            function( a )
            {
                var pagesAlreadySeen = {};

				for (var i = 0; i < a.length; i += 1) {

                    var href = a[i].page.value;

					if( ! pagesAlreadySeen[ a[i].page.value ] )
					{
						pagesAlreadySeen[ a[i].page.value ] = i;
					}
        
                    if( self.opener )
                    {
                        href = "javascript:self.opener.DESANTI.openPage( \"" +
                               href + "\" ); self.opener.focus( )";
                    }
        
                    var indice = pagesAlreadySeen[ a[i].page.value ];

					items[ indice ] = {
                      "id":    a[i].page.value,
					  "label": a[i].page.value,
                      "thumb": a[i].pageThumbnail.value,
                      "href": href
                    };

					if( items[ indice ][ a[ i ].relationLabel.value ] )
					{
	                    items[ indice ][ a[ i ].relationLabel.value ].push( decodeURIComponent( a[ i ].objectLabel.value ) );    
					}
					else
					{
	                    items[ indice ][ a[ i ].relationLabel.value ] = [ decodeURIComponent( a[ i ].objectLabel.value ) ];    
					}

	                if( !( properties.hasElem( a[ i ].relationLabel.value ) ) )
	                {
	                    properties.push( a[ i ].relationLabel.value );
	                }
                }
            }, false, true );
    };

    window.onload = function( )
    {
      
	  // L'identifiant de la collection est passé en paramètre de l'URL
	  D.collectionId = location.href.split( "?" )[ 1 ].split( "&" )[ 0 ].split( "=" )[ 1 ];  
    
	  findPredicates( );
    
      var facets = document.getElementById( "facets");
      for( var i = 0 ; i < properties.length ; i += 1 )
      {
          var facet = document.createElement( "div" );
          var expression = "." + properties[ i ];
      
          facet.setAttribute( "ex:role", "facet" );
          facet.setAttribute( "ex:expression", expression );
          facet.setAttribute( "ex:facetLabel", decodeURIComponent( properties[ i ] ) );
      
          facets.appendChild( facet );
      }
      
      window.database = Exhibit.Database.create(); 
      var data = {"items": items};
      window.database.loadData(data); 
      window.exhibit = Exhibit.create(); 
      window.exhibit.configureFromDOM(); 
    }

} ) ( DESANTI );
